<?php

class Itvina_Controller_Action_Helper_Action extends Zend_Controller_Action_Helper_Abstract
{
	public $pluginLoader;

	public function __construct()
	{
		$this->pluginLoader = new Zend_Loader_PluginLoader ();
	}

	function direct($function, $params = array())
	{
		return $function ( func_get_args () );
	}

	public function delete($model, $after_function_name = "", $before_function_name = "")
	{
		$controller = $this->_actionController;
		if ($controller->getRequest ()->isPost ())
		{
			$check = true;
			if ($before_function_name != "")
				$check = $controller->$before_function_name ();
			if ($check)
			{
				$arr_id = ( array ) $controller->getRequest ()->getParam ( 'id' );				
				if (count ( $arr_id ) > 0)
				{
					if (is_string ( $model ))
						$class = $model;
					else if ($model instanceof Itvina_Model_Abstract)
						$class = get_class ( $model );
					$object = new $class ();
					if ($object->deleteBase ( $arr_id ) > 0)
					{
						$controller->getHelper ( 'flashMessenger' )->direct ( 'Xóa thành công!' );
					}
					else
					{
						$controller->getHelper ( 'flashMessenger' )->direct ( 'Xóa không thành công. Xin vui lòng thử lại!' );
					}
				}
			}
			if ($after_function_name != "")
				$controller->$after_function_name ();
		}
		$controller->getHelper ( 'redirector' )->gotoUrl ( $_SERVER [HTTP_REFERER] );
	}

	public function publish($model, $column, $function_name = "")
	{
		$controller = $this->_actionController;
		if ($controller->getRequest ()->isPost ())
		{
			$arr_id = ( array ) $controller->getRequest ()->getParam ( 'id' );
			if (count ( $arr_id ) > 0)
			{
				if (is_string ( $model ))
					$class = $model;
				else if ($model instanceof Itvina_Model_Abstract)
					$class = get_class ( $model );
				$object = new $class ();
				$publish_status = $controller->getRequest ()->getParam ( 'publish_status' );
				$action_string = ( string ) $publish_status == '1' ? 'Kích hoạt' : 'Bỏ kích hoạt';
				$object->$column = $publish_status;
				try
				{
					$object->updateBase ( $arr_id );
					$controller->getHelper ( 'flashMessenger' )->direct ( "$action_string thành công!" );
				}
				catch ( Exception $e )
				{
					$controller->getHelper ( 'flashMessenger' )->direct ( "$action_string không thành công. Xin vui lòng thử lại!" );
				}
			}
			if ($function_name != "")
				$controller->$function_name ();
		}
		$controller->getHelper ( 'redirector' )->gotoUrl ( $_SERVER [HTTP_REFERER] );
	}

	public function saveOrder($model, $column)
	{
		$controller = $this->_actionController;
		if ($controller->getRequest ()->isPost ())
		{
			$arr_order = ( array ) $controller->getRequest ()->getParam ( 'orderer' );
			if (count ( $arr_order ) > 0)
			{
				try
				{
					if (is_string ( $model ))
						$class = $model;
					else if ($model instanceof Itvina_Model_Abstract)
						$class = get_class ( $model );
					$object = new $class ();
					foreach ( $arr_order as $id => $order )
					{						
						$object->$column = $order;
						$object->updateBase ( $id );
					}
					$controller->getHelper ( 'flashMessenger' )->direct ( "Sắp xếp thứ tự thành công!" );
				}
				catch ( Exception $e )
				{
					$controller->getHelper ( 'flashMessenger' )->direct ( "Sắp xếp thứ tự không thành công. Xin vui lòng thử lại!" );
				}
			}
		}
		$controller->getHelper ( 'redirector' )->gotoUrl ( $_SERVER [HTTP_REFERER] );
	}
	
	public function getActionList($url="")
	{
		//lấy danh sách tính năng hiện tại của ứng dụng
		//duyệt các folder controllers của từng module
		$resources = array ();
		$str_action_url = ""; //chuỗi chứa danh sách các url của action. ví dụ: 'index/index/index','admin/index/header',...
		$str_module_name = ""; //chuỗi chứa danh sách tên các module. ví dụ: 'index','admin',...
		$str_controller_url = ""; //chuỗi chứa danh sách các url của controller. ví dụ: 'index/index','admin/index',...
		$controller_dir = $this->_actionController->getFrontController ()->getControllerDirectory ();
		foreach ( $controller_dir as $module_name => $controller_path )
		{
			$module_name=strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1-$2", $module_name)); //chuyển thành dạng đường dẫn. VD: book-image
			
			//luu chuỗi module
			if ($str_module_name != "")
				$str_module_name .= ",";
			$str_module_name .= "'$module_name'";
			
			//duyệt các file *Controller.php trong folder controllers
			$controller_files = new DirectoryIterator ( $controller_path );
			$controllers = array ();
			foreach ( $controller_files as $controller_file )
			{
				if ($controller_file->isFile ()) //kiểm tra phải là file
				{
					$controller_file_name = $controller_file->getFilename ();
					if (strstr ( $controller_file_name, 'Controller.php' ) == 'Controller.php') //kiểm tra tên file kết thúc bằng Controller.php
					{
						//luu chuỗi url của controller
						$controller_name = strtolower ( str_replace ( 'Controller.php', '', $controller_file_name ) );
						$controller_name=strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1-$2", $controller_name)); //chuyển thành dạng đường dẫn. VD: admin-view-all						
						if ($str_controller_url != "")
							$str_controller_url .= ",";
						$str_controller_url .= "'$module_name/$controller_name'";
						
						//đọc file tìm các phương thức có dạng *Action
						$controller_file_path = $controller_path . '/' . $controller_file_name;
						$tokens = token_get_all ( file_get_contents ( $controller_file_path ) );
						$class_found = 0; //cờ = 1 khi tìm thấy class, = 2 khi tìm thấy class có dạng *Controller
						$function_found = false;
						$actions = array ();
						foreach ( $tokens as $token )
						{
							if (! is_array ( $token ))
								continue;
							
							//tìm class
							if ($token [0] == T_CLASS)
							{
								$class_found = 1;
								if ($class_found == 2)
									break;
							}
							else if ($class_found == 1 && $token [0] == T_STRING && strstr ( $token [1], 'Controller' ) == 'Controller')
							{
								$class_found = 2;
							}
							
							//tìm function
							if ($token [0] == T_FUNCTION)
							{
								$function_found = true;
							}
							else if ($class_found == 2 && $function_found && $token [0] == T_STRING)
							{
								$function = $token [1];
								if (strstr ( $function, 'Action' ) == 'Action')
								{
									//luu chuỗi url của action
									$action_name = str_replace ( 'Action', '', $function );
									$action_name = strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1-$2", $action_name)); //chuyển thành dạng đường dẫn. VD: book-image
									$action_url = $module_name . "/" . $controller_name . "/" . $action_name;
									if ($str_action_url != "")
										$str_action_url .= ",";
									$str_action_url .= "'$action_url'";
									
									//cho vào mảng $controllers
									$actions [$action_name] ['action_name'] = $action_name;
								}
								$function_found = false;
							}
						}
						
						//cho vào mảng $controllers
						$controllers [$controller_name] ['actions'] = $actions;
					}
				}
				
				//cho vào mảng $resources
				$resources [$module_name] ['controllers'] = $controllers;
			}
		}
		
		//đồng bộ danh sách module chương trình với danh sách module trong csdl
		$module = new Admin_Model_Module ();
		$where = "module_name NOT IN ($str_module_name)";
		$module->deleteAllBase ( $where );
		$modules = $module->fetchAllBase ();
		$i = 1;
		foreach ( $resources as $module_name => $value )
		{
			$module_found = false;
			$module_note = "";
			foreach ( $modules as $module )
			{
				if ($module->module_name == $module_name)
				{
					$module_note = $module->module_note;
					$module_found = true;
					$module_id=$module->module_id;
					break;
				}
			}
			if (! $module_found)
			{
				$module = new Admin_Model_Module ();
				$module->module_name = $module_name;
				$module->insertBase ();
				$module_id=$module->module_id;
			}
			$resources [$module_name] ['module_id'] = $module_id;
			$resources [$module_name] ['module_note'] = $module_note;
			$resources [$module_name] ['module_order'] = $i;
			$i ++;
		}
		
		//đồng bộ danh sách controller chương trình với danh sách controller trong csdl
		$controller = new Admin_Model_Controller ();
		$where = "controller_url NOT IN ($str_controller_url)";
		$controller->deleteAllBase ( $where );
		$controllers = $controller->fetchAllBase ();
		$i = 1;
		foreach ( $resources as $module_name => $value )
		{
			$j = 1;
			foreach ( $value ['controllers'] as $controller_name => $value2 )
			{
				$controller_found = false;
				$controller_note = "";
				$controller_url = $module_name . "/" . $controller_name;
				foreach ( $controllers as $controller )
				{
					if ($controller->controller_url == $controller_url)
					{
						$controller_found = true;
						$controller_note = $controller->controller_note;
						$controller_id = $controller->controller_id;
						break;
					}
				}
				if (! $controller_found)
				{
					$controller = new Admin_Model_Controller ();
					$controller->controller_name = $controller_name;
					$controller->controller_url = $controller_url;
					$controller->insertBase ();
					$controller_id = $controller->controller_id;
				}
				$resources [$module_name] ['controllers'] [$controller_name] ['controller_id'] = $controller_id;
				$resources [$module_name] ['controllers'] [$controller_name] ['controller_note'] = $controller_note;
				$resources [$module_name] ['controllers'] [$controller_name] ['controller_order'] = $i . "." . $j;
				$j ++;
			}
			$i ++;
		}
		
		//đồng bộ danh sách action chương trình với danh sách action trong csdl
		$action = new Admin_Model_Action ();
		$where = "action_url NOT IN ($str_action_url)";
		$action->deleteAllBase ( $where );
		$actions = $action->fetchAllBase ();
		$i = 1;
		foreach ( $resources as $module_name => $value )
		{
			$j = 1;
			foreach ( $value ['controllers'] as $controller_name => $value2 )
			{
				$k = 1;
				foreach ( $value2 ['actions'] as $action_name => $value3 )
				{
					$action_found = false;
					$action_note = "";
					$action_url = $module_name . "/" . $controller_name . "/" . $action_name;
					foreach ( $actions as $action )
					{
						if ($action->action_url == $action_url)
						{
							$action_found = true;
							$action_note = $action->action_note;
							$action_id = $action->action_id;
							break;
						}
					}
					if (! $action_found)
					{
						$action = new Admin_Model_Action ();
						$action->action_name = $action_name;
						$action->action_url = $action_url;
						$action->insertBase ();
						$action_id = $action->action_id;
					}					
					$resources [$module_name] ['controllers'] [$controller_name] ['actions'] [$action_name] ['action_id'] = $action_id;
					$resources [$module_name] ['controllers'] [$controller_name] ['actions'] [$action_name] ['action_note'] = $action_note;
					$resources [$module_name] ['controllers'] [$controller_name] ['actions'] [$action_name] ['action_url'] = $action_url;
					$resources [$module_name] ['controllers'] [$controller_name] ['actions'] [$action_name] ['action_order'] = $i . "." . $j . "." . $k;
					if($url!="")
						if($action_url==$url)
							return $resources [$module_name] ['controllers'] [$controller_name] ['actions'] [$action_name];	
					$k ++;
				}
				$j ++;
			}
			$i ++;
		}
		
		return $resources;
	}
	
	public function getAction($url)
	{
		return $this->getActionList($url);
	}
}
